package com.zzptc.my.bookreader.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.zzptc.my.bookreader.Adapter.BookAdapter;
import com.zzptc.my.bookreader.Bean.Book;
import com.zzptc.my.bookreader.Bean.ChooseBook;
import com.zzptc.my.bookreader.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ListView booklv;
     BookAdapter adapter;
     List<Book>bookList=new ArrayList<>();
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
    initView(root);
setListener();
        return root;
    }

    private void setListener() {
        booklv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
                SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                int uid=sp.getInt("userid",-1);
                int bid=bookList.get(i).getId();
                if (ifChooseBook(uid,bid)){
                    new ChooseBook(0,uid,bid).save();//添加进数据表中
                    showToast("收藏成功");
                }
                test();//简易看效果
                return false;
            }
        });
    }

    private void test() {
        for (ChooseBook c:LitePal.findAll(ChooseBook.class)){
            Log.e("choosebook",c.getUserid()+" "+c.getBookid());
        }
    }

    //判断表中是否重复
    private boolean ifChooseBook(int uid,int bid){
        for (ChooseBook c:LitePal.findAll(ChooseBook.class)){
            if (c.getUserid()==uid&&c.getBookid()==bid){
                return false;
            }
        }
        return true;
    }

    private void initView(View root) {
        booklv=root.findViewById(R.id.booklv);
        bookList= LitePal.findAll(Book.class);
        adapter=new BookAdapter(getContext(),R.layout.book_item,bookList);
        booklv.setAdapter(adapter);
    }
    private void showToast(String str){
        Toast.makeText(getContext(),str, Toast.LENGTH_SHORT).show();
    }
}